import { render } from 'amis'
import axios from 'axios'
import copy from 'copy-to-clipboard'
import { toast } from 'amis-ui'
import allBus from 'core/bus'
import allLs from 'core/ls'

// amis 环境配置
const env = {
  /**
   * , {
    url, // 接口地址
    method, // 请求方法 get、post、put、delete
    data, // 请求数据
    responseType,
    config, // 其他配置
    headers // 请求头
  }
   * @param {*} c 
   * @returns 
   */
  // 下面三个接口必须实现
  fetcher: (c) => {
    console.log('c', c);
    c.url = 'https://api.wrshg.com/mgt-center' + c.url
    c.config = c.config || {}
    // c.config.withCredentials = false
    c.responseType && (c.config.responseType = c.responseType)

    if (c.config.cancelExecutor) {
      c.config.cancelToken = new axios.CancelToken(c.config.cancelExecutor)
    }

    c.config.headers = c.headers || {}
    const authToken = allLs.common.token.get()
    if (authToken) {
      c.config.headers['Auth-Token'] = authToken
    }
    if (c.method !== 'post' && c.method !== 'put' && c.method !== 'patch') {
      if (c.data) {
        c.config.params = c.data
      }
      return sendAjax(c.method, c.url, c.data, c.config)
    } else if (c.data && c.data instanceof FormData) {
      c.config.headers = c.config.headers || {}
      c.config.headers['Content-Type'] = 'multipart/form-data'
    } else if (
      c.data &&
      typeof c.data !== 'string' &&
      !(c.data instanceof Blob) &&
      !(c.data instanceof ArrayBuffer)
    ) {
      c.data = JSON.stringify(c.data)
      c.config.headers = c.config.headers || {}
      c.config.headers['Content-Type'] = 'application/json'
    }

    return sendAjax(c.method, c.url, c.data, c.config)
  },
  isCancel: (value) => axios.isCancel(value),
  copy: (content) => {
    copy(content)
    toast.success('内容已复制到粘贴板')
  }
}

function sendAjax(method, url, data, config) {
  return axios[method](url, data, config).then((res) => {
    console.log('res', res)
    if (res.data && res.data.code === -1000) {
      // allBus.common.loginExpire.emit()
    }
    res.status = res.code
    return res
  })
}

export function renderAmis(schema) {
  return render(schema, {}, env)
}
